//
//  COBalanceController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/10.
//

import UIKit
import WebKit

class COBalanceController: COBaseController {
    
    var webView: WKWebView!
    var wallets = [COBalanceModel]() // 内购列表
    
    lazy var walletHeadView: COBalanceHeadView = {
        let head = COBalanceHeadView(frame: CGRectMake(0, 0, SCREENWIDTH, PTW(140)))
        head.isHidden = true
        return head
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.post(name: .NewUserRechargeNotification, object: nil, userInfo: ["type":1])
        NotificationCenter.default.post(name: .RandomTimeRunNotification, object: nil, userInfo: ["type":1])
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.post(name: .NewUserRechargeNotification, object: nil, userInfo: ["type":0])
        NotificationCenter.default.post(name: .RandomTimeRunNotification, object: nil, userInfo: ["type":0])
    }
    
    lazy var baseTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = .clear
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 11.0, *) {
            if #available(iOS 13.0, *) {
                tableView.automaticallyAdjustsScrollIndicatorInsets = false
            }else{
                tableView.contentInsetAdjustmentBehavior = .never
            }
        }else {
            automaticallyAdjustsScrollViewInsets = false
        }
        tableView.tableHeaderView = self.walletHeadView
        return tableView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.addnav()
        self.title = "Wallet"
        let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
        if (feed == true){
            creatWithType(type: 1)
            return
        }else{
            COHttpManager.request(target: COBaseApi.privacyPolicyV2, modelType: COPolicyWalletModel.self) { [weak self] code, object, success in
                let model = object
                if (model?.open == true){
                    self?.creatWithType(type: 2)
                    return
                }
                self?.creatWithType(type: 1)
            } failureBlock: {[weak self] code, msg in
                self?.creatWithType(type: 1)
            }
        }
    }

    func creatWithType(type:Int){
        if (type == 2){
            // 创建 WKWebViewConfiguration 对象
            let config = WKWebViewConfiguration()
            // 根据配置创建 WKWebView 对象
            webView = WKWebView(frame: CGRect(x: 0, y: KStatusAndNavBarHeight, width: SCREENWIDTH, height: SCREENHEIGHT - KStatusAndNavBarHeight), configuration: config)
            webView.navigationDelegate = self
            
            guard let token = COUserInfoManager.shared.curUser?.token else {
                return
            }
            // 设置需要加载的 H5 页面的 URL
            let url = URL(string: "\(KbaseUrl)/api/v1/app/client/agreement/privacy-policy?t=\(token)&os=1&v=\(KBundleVersion)&p=H1&uid=\(HDeviceIdentifier.deviceIdentifier())")
            // 创建一个 URLRequest 对象
            let request = URLRequest(url: url!)
            // 加载页面
            webView.load(request)
            // 将 WebView 添加到视图中
            view.addSubview(webView)
            UIToolHelper.showHUD()
        }else{
            getPriceList()
            self.view.addSubview(self.baseTableView)
            self.baseTableView.snp.makeConstraints { make in
                make.left.right.bottom.equalToSuperview()
                make.top.equalToSuperview().offset(KStatusAndNavBarHeight)
            }
        }
    }
    
    func getPriceList(){
        var params = [String:Any]()
        params["platform"]  = 2
        params["uuid"] = HDeviceIdentifier.deviceIdentifier()
        UIToolHelper.showHUD()
        COHttpManager.request(target: COBaseApi.priceList(param: params), modelType: COBalancePriceModel.self) {[weak self] code, object, success in
            UIToolHelper.hideHUD()
            self?.wallets.removeAll()
            self?.wallets = object?.prices ?? [COBalanceModel]()
            self?.baseTableView.reloadData()
            self?.walletHeadView.isHidden = false
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
            UIToolHelper.makeToast("Network error,plesase try again later!")
        }
    }
}


extension COBalanceController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return self.wallets.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = COBalanceViewCell().cellWithTableView(tableView)
        cell.selectionStyle = .none
        cell.model = self.wallets[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return PTW(94)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = wallets[indexPath.row]
        guard model.productId != nil else {
            return
        }
        UIToolHelper.showHUD()
        AppPurchaseManager.pay(purchaseProductId: model.productId!) { [weak self] result in
            UIToolHelper.hideHUD()
            if (result == true){
                UIToolHelper.makeToast("Successful!")
                self?.updateMybalance()
                self?.getPriceList()
                COKVATrackerEvent.shared().clickBuyCoinsEvent(String(format: "%.2f", model.price))
            }else{
                UIToolHelper.makeToast("Fail,please try again later!")
            }
        }
    }
    
    // 刷新我的金币数
    func updateMybalance(){
        COHttpManager.request(target: COBaseApi.mybalance, modelType: COMyBalanceModel.self) {[weak self] code, data, success in
            var model = COUserInfoManager.shared.curUser
            model?.userResponse.balance = data?.coins ?? 0
            COUserInfoManager.shared.curUser = model
            COUserInfoManager.coSaveInfo()
            self?.walletHeadView.updateBalance()
        } failureBlock: { code, msg in
            print(msg as Any)
        }
    }
}

extension COBalanceController:WKNavigationDelegate{
    
    // MARK: - WKNavigationDelegate methods
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("Failed to load webpage with error: \(error)")
        UIToolHelper.hideHUD()
        if (error as NSError?) != nil{
            UIToolHelper.makeToast("Page loading failed.Try again later!")
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                // 在延迟指定秒数后执行的代码
                self.navigationController?.popViewController(animated: true)
            }
        }
    }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("Failed to complete webpage navigation with error: \(error)")
        UIToolHelper.hideHUD()
        if (error as NSError?) != nil {
            UIToolHelper.makeToast("Page loading failed.Try again later!")
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                // 在延迟指定秒数后执行的代码
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        UIToolHelper.hideHUD()
        guard let url = navigationAction.request.url else {
            decisionHandler(.allow)
            return
        }
        print("url ------- \(url.absoluteString)")
        if (url.absoluteString.count > 0){
            if (url.absoluteString.contains("pay-success.html")){
                // 取消跳转
                AppPurchaseManager.updateBalance()
                UIToolHelper.makeToast("Successful!")
                let orderStr = "orderAmount="
                if let range = url.absoluteString.range(of: orderStr) {
                    let startIndex = url.absoluteString.index(range.lowerBound, offsetBy: orderStr.count)
                    let suffix = url.absoluteString.suffix(from: startIndex)
                    print("suffix --- \(suffix)")
//                    KVATrackerEvent.shared().clickBuyCoinsEvent(String(suffix))
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    // 在延迟指定秒数后执行的代码
                    self.navigationController?.popViewController(animated: true)
                }
                decisionHandler(.cancel)
            }else if (url.absoluteString.contains("pay-fail.html")){
                // 取消跳转
                UIToolHelper.makeToast("Payment Failed!")
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    // 在延迟指定秒数后执行的代码
                    self.navigationController?.popViewController(animated: true)
                }
                decisionHandler(.cancel)
            }else{
                // 允许跳转
                decisionHandler(.allow)
            }
        }else{
            // 允许跳转
            decisionHandler(.allow)
        }
    }

}
